package com.rytx.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.diagnosis.DiagnosisUtils;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.rytx.common.config.MyAliPayConfig;
import com.rytx.common.core.domain.model.ArtUser;
import com.rytx.common.core.redis.RedisCache;
import com.rytx.common.utils.alipay.AlipayConfigUtil;
import com.rytx.system.mapper.ArtUserMapper;
import com.rytx.system.service.IAliRepService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class IAliRepServiceImpl implements IAliRepService {
    private static final Logger log = LoggerFactory.getLogger(IAliRepServiceImpl.class);
    private static final String CODE_SUCCESS = "10000";
    private static final String CODE_FAILURE = "20000";

    @Autowired
    private MyAliPayConfig myAliPayConfig;
    @Autowired
    private ArtUserMapper artUserMapper;
    @Autowired
    private RedisCache redisCache;
    @Override
    public AlipaySystemOauthTokenResponse getAlipayOAuthToken(String code, MyAliPayConfig config) throws AlipayApiException {
        if(StrUtil.isBlank(code))return null;
        String gtype = "authorization_code";//授权码方式
        // 初始化SDK
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigUtil.init(config));
        // 构造请求参数以调用接口
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
//        if(("authorization_code").equals(gtype)){
            request.setRefreshToken("");//grant_type=authorization_code 不填
            // 设置授权码
            request.setCode(code);//授权码，用户对应用授权后得到。本参数在 grant_type 为 authorization_code 时必填；为 refresh_token 时不填。
            // 设置授权方式
//        }
//        else if(("refresh_token").equals(gtype)){
//            //TODO 这里需要将上次请求返回的token作为refresh_token 具体操作建议存如redis中时常设置为1小时
//            String token = redisCache.getCacheObject("");
//            request.setRefreshToken(token);//grant_type=authorization_code 不填
//            // 设置授权码
//            request.setCode("");//授权码，用户对应用授权后得到。本参数在 grant_type 为 authorization_code 时必填；为 refresh_token 时不填。
//        }
        request.setGrantType(gtype);//用授权码来换取授权令牌: authorization_code 或用刷新令牌来换取一个新的授权令牌: refresh_token
        AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
        log.info("getAlipayOAuthToken:调用成功:{}",response.getBody());
        // 调用成功
        if (response.isSuccess()) {
            redisCache.setCacheObject(response.getOpenId(), response.getAccessToken(), 3600, TimeUnit.SECONDS);
            log.info("getAlipayOAuthToken:调用成功:{}",response.getBody());
        } else {
            String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
            log.info("诊断链接: {}" , diagnosisUrl);
        }
        return response;
    }
    // 获取用户信息
    @Override
    public String getUserInfo(AlipaySystemOauthTokenResponse evaluateModel) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigUtil.init(myAliPayConfig));
        AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse response = alipayClient.execute(request,evaluateModel.getAccessToken());
        log.info("getUserInfo:调用成功:{}",response.getBody());
        if(response.isSuccess()){
            // 保存用户信息
            if(CODE_SUCCESS.equals(response.getCode())) {
                ArtUser user = new ArtUser();
                user.setAliOpenId(response.getOpenId());
                if(artUserMapper.selectArtUserList(user).isEmpty()) {
                    ArtUser artUser = new ArtUser();
                    artUser.setUserName(StrUtil.isBlank(response.getNickName()) ? "匿名用户" : response.getNickName());
                    artUser.setUserAvatarUrl(response.getAvatar());
                    artUser.setAliOpenId(response.getOpenId());
                    artUser.setUserGender(response.getGender());
                    artUser.setCity(response.getCity());
                    artUser.setProvince(response.getProvince());
                    int i = artUserMapper.insertArtUser(artUser);
                    if (i > 0) {
                        log.info("保存用户信息成功");
                    } else {
                        log.info("保存用户信息失败");
                    }
                }
            }
        }
        return response.getOpenId();
    }

}
